package com.action;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.jdom.Element;

import com.bean.User;
import com.bean.XmlBean;
import com.ibatis.common.logging.jakarta.JakartaCommonsLoggingImpl;
import com.interfaces.service.BaseService;
import com.opensymphony.xwork2.ActionSupport;
import com.pub.GloabPara;
import com.util.ConfigUtil;
import com.util.FreeMarkerHelper;
import com.util.PaginatedArrayList;
import com.util.PaginatedList;
import com.util.XmlHelp;
/**
 * 
 * <p>功能描述:Action基类</p>
 * @author  <a href="mailto: zhuyoulong@gtss.com.cn">zhuyoulong</a>
 * @create_date 2008-10-23
 * @version $ Revision: 1.0
 */
@SuppressWarnings("serial")
public class BaseAction extends ActionSupport {
	protected Log logger = LogFactory.getLog(BaseAction.class);
	/**
	 * 主要是用于直接调用执行SQL语句的接口服务
	 */
	protected BaseService baseService;
	public String page="";
	/**
	 * 第几页,默认第一页
	 */
	protected int pageNo = GloabPara.pageNo;
	/**
	 * 默认每页20条记录
	 */
	protected int pageSize = GloabPara.pageSize;
	protected String IMG = GloabPara.IMG;
	protected String error;
	/**
	 * 在action中用于return到index
	 */
	public static final java.lang.String INDEX = "index";
	/**
	 * <p>在action中用于return到login</p>
	 * <p>一般指的是登录页面</p>
	 */
	public static final java.lang.String LOGIN = "login";
	public static final java.lang.String MYACCOUNT = "myaccout";
	/**
	 * <p>在action中用于return到message</p>
	 * <p>一般指的是信息提示页面</p>
	 */
	public static final java.lang.String MESSAGE = "message";
	/**
	 * <p>提示信息,一般用于提示用户的错误操作或成功操作</p>
	 * <p>example：message="你的操作成功完成";return MESSAGE;</p>
	 */
	protected String message;
//	public User user;
	/**
	 * 获得用户session :user
	 */
	public User getSessionUser(){
		Object obj = this.getSession().getAttribute("user");
		if(obj!=null){
			 return (User)obj;
		}
		else{
			return null;
		}
	}
	/**
	 * 通过id获得id数组
	 * @param id
	 * @return
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public List getIds(Long id){
    	List ids = new ArrayList();
    	ids.add(id);
    	return ids;
	}
	public String getPage() {
		return page;
	}
	public void setPage(String page) {
		this.page = page;
	}
	/**
	 * <p>功能描述：获得request对象</p>
	 * @return
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	
	/**
	 * <p>功能描述：获得response对象</p>
	 * @return
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}
	/**
	 * 
	 * <p>功能描述：获得session对象</p>
	 * @return
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public HttpSession getSession() {
		return getRequest().getSession();
	}
	/**
	 * 获得context上下文
	 * @return
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public ServletContext getServletContext() {
		return ServletActionContext.getServletContext();
	}
	
	
	/**
	 * <p>功能描述：根据cookie名称获得cookie值</p>
	 * @param cookiename
	 * @return
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public String getCookie(String cookiename) {
		String cookieValue = "";
		Cookie cookies[] = getRequest().getCookies();
		Cookie sCookie = null;
		if (cookies != null && cookies.length > 0) {
			for (int i = 0; i < cookies.length; i++) {
				sCookie = cookies[i];
				sCookie.setPath("/");
				if (sCookie.getName().equals(cookiename)) {
					cookieValue = sCookie.getValue();
					break;
				}
			}
		}
		return cookieValue;
		
	}
	/**
	 * 创建页面
	 * @param sourceFile 模板文件名(如 ***.ftl )
	 * @param targetFile 生成目标文件名(如 ***.shtml )
	 * @param root map 数据
	 * @param targetPath 存放路劲,后面必须有 "/" 结尾
	 */
	public void template(String sourceFile, String targetFile, Map root, String sourcePath, String targetPath) {
		String target_path = this.getServletContext().getRealPath("/");
		FreeMarkerHelper fh = new FreeMarkerHelper(
				this.getServletContext().getRealPath("/")
						+ ConfigUtil.getConfigPropertyValue(sourcePath)); // 模板路径
		fh.createStaticPage(root, sourceFile, target_path+ targetPath,targetFile);
	}
	/**
	 * 
	 * <p>功能描述：获得当前服务器的path目录的绝对路径</p>
	 * @param path
	 * @return
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public String getRealyPath(String path) {
		return getServletContext().getRealPath(path);
	}
	
	/**
	 * 
	 * <p>功能描述：通过key值获得默认配置文件config.properties中某个key对应的值</p>
	 * @param key
	 * @return key对应的值

	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public  String getConfigPropertyValue(String key){
		return ConfigUtil.getConfigPropertyValue(key);
	}
	
	public  String getMyConfigPropertyValue(String key){
		return ConfigUtil.getMyConfigPropertyValue(key);
	}
	
	/**
	 * 
	 * <p>功能描述：通过key值获得指定配置文件中某个key对应的值</p>
	 * @param filename
	 * @param key
	 * @return
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public  String getOtherPropertyValue(String filename,String key){
		return ConfigUtil.getOtherPropertyValue(filename,key);
	}
	/**
	 * 
	 * <p>功能描述：获得分页字符串</p>
	 * @param list
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public void page(PaginatedList list){
//		com.ibatis.common.logging.jakarta.JakartaCommonsLoggingImpl.debug("");
		JakartaCommonsLoggingImpl imp = new JakartaCommonsLoggingImpl(BaseAction.class);
		imp.debug("test - test");
		page = PaginatedArrayList.getPage(list);
	}
	/**
	 * 论坛版分页标签
	 * @param list
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public void pageForum(PaginatedList list){
		page = PaginatedArrayList.getPageForum(list);
	}
	/**
	 * 生成静态页面方法
	 * @param root :map对象
	 * @param sourceFile 模板文件
	 * @param targetFile 目标文件
	 * @param sourcePathKey 模板路径的properties变量
	 * @param targetPathKey 目标路径的properties变量
	 * @param folderId 文件夹id
	 * @return boolean
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	protected boolean createHtml(Map root, String sourceFile, String targetFile, String sourcePathKey, String targetPathKey, String folderId)
    {
        try
        {
            FreeMarkerHelper freemarker = new FreeMarkerHelper((new StringBuilder(String.valueOf(getServletContext().getRealPath("/")))).append(ConfigUtil.getConfigPropertyValue(sourcePathKey)).toString());
            freemarker.createStaticPage(root, sourceFile, (new StringBuilder(String.valueOf(getServletContext().getRealPath("/")))).append(ConfigUtil.getConfigPropertyValue(targetPathKey)).append(folderId).append("/").toString(), targetFile);
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return false;
        }
        return true;
    }
	/**
	 * 通过xml路径获得param下节点数组
	 * @param path xml路径
	 * @return List
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
    public List getXmlList(String path)
    {
        String xmlPath = getRealyPath(path);
        List elementList = new ArrayList();
        List list = XmlHelp.findAllChildEle(xmlPath, "param");
        for(int i = 0; i < list.size(); i++)
        {
            Element element = (Element)list.get(i);
            XmlBean xmlBean = new XmlBean();
            xmlBean.setId(element.getAttributeValue("id"));
            xmlBean.setValue(element.getAttributeValue("value"));
            elementList.add(xmlBean);
        }

        return elementList;
    }
    /**
     * <p>功能描述：通过XML 路径和XML ID查找XML值</p>
     * @param path xml路径
     * @param id 节点
     * @return
     * @author:zhuyoulong
     * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
     */
    public String getValueByXmlId(String path,String id){
    	String xmlPath = getRealyPath(path);
    	String xmlValue = "";
        List list = XmlHelp.findAllChildEle(xmlPath, "param");
        int SIZE = list.size();
        for(int i = 0; i < SIZE; i++)
        {
            Element element = (Element)list.get(i);
            String xmlId = element.getAttributeValue("id");
            xmlValue = element.getAttributeValue("value");
            if(xmlId.equals(id)){
            	break;
            }
        }    	
    	return xmlValue;
    }
    /**
     * String... args这是java5的新写法,一般出现在一个方法的形参中(也就是括号里面的参数),String...表示一个String集合或数组或单个String.   
  	 * 当你传递实参的时候可以这样写XXX(List<String>),也可以XXX(String,String,String......)等多种写法
  	 * example:
		  	  String msg_temp = "长度不能大于{0}{1}K";
		      String msg_value = "10";
		      String msg_value2 = "20";
		      String msg = MessageFormat.format(key, msg_value,msg_value2);
		      System.out.println(msg);
     * @param request
     * @param key
     * @param args
     * @return
     * @author:zhuyoulong
     * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
     */
	public String getMsg(String key,Object... args){
		if(key==null||key.length()==0){
			return null;
		}
		key = this.getText(key);
		String message=null;
		if(args!=null&&args.length>0){
			message= MessageFormat.format(key, args);
		}
		return message;
	}
	
	public BaseService getBaseService() {
		return baseService;
	}
	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	}
	public int getPageNo() {
		return pageNo;
	}
	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public Log getLogger() {
	
		return logger;
	}
	public void setLogger(Log logger) {
		this.logger = logger;
	}
	public String getError() {
		return error;
	}
	public void setError(String error) {
		this.error = error;
	}
//	public User getUser() {
//		return user;
//	}
//	public void setUser(User user) {
//		this.user = user;
//	}	
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	
	

	
}
